package com.dm.cloud.utils;

import com.dm.cloud.api.dto.Log;
import com.dm.cloud.configurations.Oauth2Utils;
import com.dm.cloud.dao.LogDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Configuration
public class MysqlLogger {

    private static LogDao logDao;

    public MysqlLogger(LogDao logDao){
        this.logDao = logDao;
    }

    public static boolean error(String infomation){
        return log(MysqlLoggerLevel.ERROR,infomation);
    }

    public static boolean warning(String infomation){
        return log(MysqlLoggerLevel.WARNING,infomation);
    }

    public static boolean info(String infomation){
        return log(MysqlLoggerLevel.INFO,infomation);
    }

    public static boolean log(MysqlLoggerLevel level,String infomation){

        try {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String authorization = request.getHeader("Authorization");
            //用户信息
            UserDetails userDetails = Oauth2Utils.getByAuthorization(authorization);

            Log mlog = new Log();
            mlog.initLog();
            mlog.setUserName(userDetails.getUsername());
            mlog.setLevel(level.get());
            mlog.setInfo(infomation);

            long effects = logDao.insert(mlog);

            if (effects > 0){
                return true;
            }
        }catch (Exception ex){
            log.error(String.format("操作信息【%s】落库失败！",infomation));
        }

        return false;
    }

}
